package com.mijie.homi.api;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mijie.core.Status;
import com.mijie.homi.common.constant.HomiStatusCode;
import com.mijie.homi.common.domain.reports.Crash;
import com.mijie.homi.common.domain.reports.Feedback;
import com.mijie.homi.common.domain.reports.Prosecute;
import com.mijie.homi.common.domain.user.DeviceInfo;
import com.mijie.homi.common.domain.user.User;
import com.mijie.homi.common.domain.user.UserExtInfo;
import com.mijie.homi.service.common.MixService;
import com.mijie.homi.service.reports.ReportService;
import com.mijie.homi.service.session.SessionService;
import com.mijie.homi.service.user.DeviceInfoService;
import com.mijie.homi.service.user.UserExtInfoService;
import com.mijie.homi.service.user.UserService;
import com.mijie.homi.util.ServerHelper;
import com.mijie.util.DateUtil;
import com.mijie.util.HttpUtil;
import com.mijie.util.IOUtil;


@Controller
@RequestMapping("/report")
public class ReportApi {

	@Autowired
	private ReportService reportService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserExtInfoService userExtInfoService;
	@Autowired
	private MixService mixService;
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private SessionService sessionService;
	
	private Logger logger = Logger.getLogger(ReportApi.class);
	
	
	@RequestMapping(value="/prosecute",method=RequestMethod.POST)
	public @ResponseBody void prosecute(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		Integer userId = ServerHelper.getUserId(request);
		JSONObject json = JSONObject.fromObject(content);
		Prosecute prosecute = (Prosecute) JSONObject.toBean(json, Prosecute.class);
		User defendant = userService.getUserById(prosecute.getDefendant());
		Status status = new Status(request,response);
		User self = userService.getUserById(userId);
		
		if(defendant==null){
			status.setCode(HomiStatusCode.USER_NOT_FOUND);
		}else{
			prosecute.setDefendantName(defendant.getNickName());
			prosecute.setPlaintiff(userId);
			prosecute.setPlaintiffName(self.getNickName());
			prosecute.setCreateAt(new Date());
			int rows = reportService.addProsecute(prosecute);
			if(rows==0) status.setCode(HomiStatusCode.API_EXCEPTION);
		}
		status.write();
	}
	
	@RequestMapping(value="/feedback",method=RequestMethod.POST)
	public @ResponseBody void feedback(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		Integer userId = ServerHelper.getUserId(request);
		User user = userService.getUserById(userId);
		JSONObject json = JSONObject.fromObject(content);
		Feedback feedback = (Feedback) JSONObject.toBean(json, Feedback.class);
		feedback.setUserId(userId);
		feedback.setUserName(user.getNickName());
		feedback.setCreateAt(new Date());
		int rows =  reportService.addFeedback(feedback);
		Status status = new Status(request,response);
		if(rows==0) status.setCode(HomiStatusCode.API_EXCEPTION);
		status.write();
	}
	
	@RequestMapping(value="/crash",method=RequestMethod.POST)
	public @ResponseBody void crash(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		JSONObject json = JSONObject.fromObject(content);
		Crash crash = (Crash) JSONObject.toBean(json, Crash.class);
		crash.setCreateAt(new Date());
		int rows =  reportService.addCrash(crash);
		Status status = new Status(request,response);
		if(rows==0) status.setCode(HomiStatusCode.API_EXCEPTION);
		status.write();
	}
	
	
	@RequestMapping(value="/terminal/active",method=RequestMethod.GET)
	public @ResponseBody void active(String deviceId,HttpServletRequest request,HttpServletResponse response) throws IOException{
		//ios传的是deviceToken,android传的是终端唯一标识
		if(deviceInfoService.getDeviceInfo(deviceId)==null){
			ServerHelper.logDeviceActive(HttpUtil.getIp(request), deviceId);
		}
		Status status = new Status(request,response);
		status.write();
	}
	
	@RequestMapping(value="/trytosignup",method=RequestMethod.GET)
	public @ResponseBody void trytosignup(String deviceId,HttpServletRequest request,HttpServletResponse response) throws IOException{
		Status status = new Status(request,response);
		status.write();
	}
	
	@RequestMapping(value="/terminal/info/update",method=RequestMethod.POST)
	public @ResponseBody void updateTerminalInfo(HttpServletRequest request,HttpServletResponse response) throws IOException{
		//android的terminalId和deviceId都是传终端唯一标识,ios传的是终端唯一标识和deviceToken
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		JSONObject json = JSONObject.fromObject(content);
		String terminalId = json.getString("terminalId").trim();
		json.remove("terminalId");
		int userId = ServerHelper.getUserId(request);
		UserExtInfo extInfo = userExtInfoService.getUserExtInfoByUserId(userId);
		DeviceInfo device = (DeviceInfo)JSONObject.toBean(json, DeviceInfo.class);
		if(device.getDeviceId().trim().isEmpty() && !terminalId.isEmpty())
			device.setDeviceId(terminalId);
		
		//打印版本号，用于统计各版本启动次数
		String appVer = device.getAppVer();
		if(appVer != null && !appVer.trim().isEmpty()){
			logger.info("@startApp@:appversion:" + appVer + ",");
		}
		
		//有可能是新终端
		Date current = new Date();
		device.setOs(device.getOs().toLowerCase());
		device.setRecentLoginAt(current);
		device.setCreateAt(current);
		device.setRecentUser(userId);
		if(!device.getDeviceId().trim().isEmpty() && !device.getDeviceId().equals("deviceTokenError")){
			deviceInfoService.addOrUpdateDeviceInfo(device);
			if(!extInfo.getDeviceId().equals(device.getDeviceId())){
				userExtInfoService.updateUserDeviceIdAndTerminalId(userId, device.getDeviceId(), terminalId);
			}
		}
		Status status = new Status(request,response);
		status.write();
	}
}
